package com.k2data.k2app.service;

import com.alibaba.fastjson.JSON;
import com.k2data.k2app.common.ResponseConstant;
import com.k2data.k2app.domain.WechatInfo;
import com.k2data.k2app.exception.K2ResponseException;
import com.k2data.k2app.mapper.WechatInfoMapper;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lidong 17-3-6.
 */
@Log4j2
@Service
public class WechatInfoService {

    private String grant_type = "authorization_code";
    private String appid = "wx23b60cdec3be3c78";
    private String secret = "f53799476e87098015008164b1ee9364";
//    private String baseUrl = "https://api.weixin.qq.com/sns/jscode2session";
    @Value("${wechat.url}")
    private String baseUrl;

    @Autowired
    private WechatInfoMapper wechatInfoMapper;

    @Transactional
    public long insert(WechatInfo wechatInfo) throws K2ResponseException {
        wechatInfo.setCreateTime(LocalDateTime.now());
        wechatInfoMapper.insertSelective(wechatInfo);
        return wechatInfo.getId();
    }
    @Transactional
    public long insert(Long userId,String code) throws K2ResponseException {
        WechatInfo wechatInfo = new WechatInfo();
        wechatInfo.setUserId(userId);
        wechatInfo.setOpenInfo(getOpenId(code));
       insert(wechatInfo);
        return wechatInfo.getId();
    }



    @Transactional
    public int delete(String code)  throws K2ResponseException {
        int num = wechatInfoMapper.deleteByOpenInfo(getOpenId(code));
        return num;
    }

    private String getOpenId(String code) throws K2ResponseException{
        StringBuffer stringBuffer = new StringBuffer(baseUrl);
        stringBuffer.append("?grant_type=").append(grant_type)
                .append("&appid=").append(appid)
                .append("&secret=").append(secret)
                .append("&js_code=").append(code);
        log.debug(stringBuffer.toString());

        try {
            RestTemplate restTemplate = new RestTemplate();
            String forObject = restTemplate.getForObject(stringBuffer.toString(), String.class);
            log.debug(forObject);
            System.out.println(forObject);
            com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(forObject);
            String openId = jsonObject.getString("openid").toLowerCase();

            return openId;
        }catch (Exception e) {
            throw new K2ResponseException(ResponseConstant.CODE_ERROR,String.format("获取openid错误",e));
        }
    }
    public Map isBand (String code) throws K2ResponseException{
        String openId= getOpenId(code);
        WechatInfo byOpenId = wechatInfoMapper.getByOpenId(openId);
        Map map = new HashMap();
        if(byOpenId == null) {
            map.put("loginFlag","1");
        }else{
            map.put("loginFlag","0");
            map.put("id", byOpenId.getUserId());
        }
        return map;
    }

}
